package com.example.download

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.DialogFragment

class UpdatingFragment : DialogFragment() {
    private val progressBar: ProgressBar by lazy {
        requireView().findViewById(R.id.pb_updating)
    }
//    private lateinit var progressText: TextView//lateinit是延迟初始化，要慎用，用lazy方法代替
    private var isDownloading = false
    private val handler = Handler(Looper.getMainLooper())
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
//        check()
//        assert()//断言（不为空），和两个感叹号的含义相同
        val view : View = inflater.inflate(R.layout.fragment_updating,container)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        startDownload()
    }
    private fun startDownload() {
        if (isDownloading) return
        isDownloading = true
        progressBar.progress = 0
//        progressText.text = "0%"
        Thread {
            try {
                for (i in 1..100) {
                    if (!isDownloading) break
                    Thread.sleep(50)
                    handler.post {
                        progressBar.progress = i
//                        progressText.text = "$i%"
                    }
                }
                handler.post {
                    if (!isDownloading) {
//                        progressText.text = "下载完成"
                    }
                    isDownloading = false
                }
            }catch (e:InterruptedException){
                handler.post{
//                    progressText.text = "下载中断"
                }
            }
        }.start()
    }
}